//
//  StoreHomePageVC.m
//  MyNewProject
//
//  Created by 王春辉 on 2020/1/4.
//  Copyright © 2020年 sun. All rights reserved.
//

#import "StoreHomePageVC.h"
#import "AuctionCollectionViewCell.h"
#import "AuctionProductDetailVC.h"

#pragma mark -- mark 数据相关
#import "StoreHomeInfoModel.h"
#import "AuctionSellModel.h"

#define MARGIN 15.0
@interface StoreHomePageVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout> {
    UILabel *_titleLabel; // 店铺名称
    UILabel *_desLabel; // 店铺描述
    UIImageView *_bannerImageView; // banner
    UIImageView *_headerImageView; // 头像
    
    int _page;
}

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) NSArray <AuctionSellDataModel *>* dataArray;
@end
static NSString *const identifier = @"cell_identifier";
@implementation StoreHomePageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.gk_navTitle = @"店铺首页";
    self.view.backgroundColor = SKColorWithHex(0xF7F7F7);
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.mas_offset(SKTopBar_Height);
        make.bottom.mas_offset(-SKBottomSafe_Height);
    }];
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_offset(0);
        make.width.mas_equalTo(self.view);
    }];
    [self requestInfoAndAuctionsData];
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestInfoAndAuctionsData)];
    self.collectionView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
}

#pragma mark -- mark 懒加载

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] init];
        _headerView.backgroundColor = [UIColor whiteColor];
        [self.collectionView addSubview:_headerView];
        UIImageView *bannerImgView = [[UIImageView alloc] initWithImage:SKIMAGE_NAMED(@"bannerPlacehoder")];
        bannerImgView.contentMode = UIViewContentModeScaleAspectFill;
        bannerImgView.layer.masksToBounds = true;
        [_headerView addSubview:bannerImgView];
        UIImageView *headerImgView = [[UIImageView alloc] initWithImage:SKIMAGE_NAMED(@"auction_treasure_shop_icon_default")];
        headerImgView.layer.cornerRadius = 30;
        headerImgView.layer.masksToBounds = true;
        [_headerView addSubview:headerImgView];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.text = @"店铺的名字";
        titleLabel.textColor = SKColorWithHex(0x333333);
        titleLabel.font = SKFONT_Medium(18);
        [_headerView addSubview:titleLabel];
        
        UILabel *desLabel = [[UILabel alloc] init];
        desLabel.text = @"店铺的描述";
        desLabel.font = SKFONT_SIZE(13);
        desLabel.textColor = SKColorWithHex(0x888888);
        [_headerView addSubview:desLabel];
        
        [bannerImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.mas_offset(0);
            make.height.mas_equalTo(self.view.mas_width).multipliedBy(120.0/375);
        }];
        
        [headerImgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(60, 60));
            make.centerX.mas_offset(0);
            make.centerY.mas_equalTo(bannerImgView.mas_bottom).mas_offset(0);
        }];
        
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_offset(0);
            make.top.mas_equalTo(headerImgView.mas_bottom).mas_offset(13);
            make.height.mas_equalTo(19);
        }];
        [desLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_offset(0);
            make.top.mas_equalTo(titleLabel.mas_bottom).mas_offset(12);
            make.height.mas_equalTo(14);
            make.bottom.mas_offset(-19);
        }];
        _bannerImageView = bannerImgView;
        _headerImageView = headerImgView;
        _titleLabel = titleLabel;
        _desLabel = desLabel;
    }
    return _headerView;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        CGFloat centerMargin = 5.0; // 中间边距
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat item_w = (self.view.width - MARGIN * 2 - centerMargin) * 0.5;
        CGFloat item_h = item_w / 170.0 * 228.0;
        layout.itemSize = CGSizeMake(item_w, item_h);
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumLineSpacing = 5;
        layout.minimumInteritemSpacing = 5;
        layout.sectionInset = UIEdgeInsetsMake(MARGIN, MARGIN, MARGIN, MARGIN);
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        [_collectionView registerClass:[AuctionCollectionViewCell class] forCellWithReuseIdentifier:identifier];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsHorizontalScrollIndicator = false;
        _collectionView.backgroundColor = self.view.backgroundColor;
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}


#pragma mark -- mark UICollectionViewDelegate, UICollectionViewDataSource

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // 详情
    AuctionCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    AuctionSellDataModel *model = self.dataArray[indexPath.item];
    cell.title = model.title;
    cell.startPrice = [model.price floatValue];
    cell.status = [model.status intValue];
    cell.sinceEndTimeInterval = model.lost_end_time;
    cell.sinceStartTimeInterval = model.lost_begin_time;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:SKIMAGE_NAMED(@"cell_default_img")];
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    AuctionSellDataModel *model = self.dataArray[indexPath.item];
    AuctionProductDetailVC *vc = [[AuctionProductDetailVC alloc] init];
    vc.sellId = model.ID;
    vc.showType = AuctionProductDetailTypeDetail;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark -- mark UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return self.headerView.size;
}


#pragma mark -- mark 获取网络数据

/// 获取商铺信息和商品列表
- (void)requestInfoAndAuctionsData {
    [self requestInfoData];
    [self requestData];
}

/// 获取商铺信息
- (void)requestInfoData {
    if (!self.shopId) {
        [self showMessage:@"无效的商铺"];
        return; }
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Shop/getshopInfo" params:@{@"id":self.shopId} reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        StoreHomeInfoModel *model = [StoreHomeInfoModel modelWithDictionary:response];
        if ([model isSuccess]) {
            [weakSelf refreshContentViewWith:model.data];
        }else {
            [weakSelf showMessage:@"获取商铺信息失败"];
        }
        [weakSelf endRefreshing];
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
        [weakSelf endRefreshing];
    }];
}

/// 获取商铺商品列表
- (void)requestData {
    _page = 1;
    SKWeakSelf;
    [self requestDataWithPage:_page Complete:^(NSArray<AuctionSellDataModel *> *models) {
        weakSelf.dataArray = models;
        [weakSelf.collectionView reloadData];
    }];
}
/// 获取更多商铺商品列表
- (void)requestMoreData {
    if (_page == 0) {
        return; }
    _page += 1;
    SKWeakSelf;
    [self requestDataWithPage:_page Complete:^(NSArray<AuctionSellDataModel *> *models) {
        NSMutableArray <AuctionSellDataModel *>* mArr = [NSMutableArray<AuctionSellDataModel *> arrayWithArray:weakSelf.dataArray];
        [mArr addObjectsFromArray:models];
        weakSelf.dataArray = mArr;
        [weakSelf.collectionView reloadData];
    }];
}

- (void)requestDataWithPage:(int)page Complete:(void(^)(NSArray <AuctionSellDataModel *>*))complete {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param addEntriesFromDictionary:@{@"page":@(page)}];
    [param addEntriesFromDictionary:@{@"shop_id":self.shopId}];
    SKWeakSelf;
    [YQNetworking getWithUrl:@"Shop/getShopGoodsList" params:param reloginRefreshBlock:^(id response) {
        
    } successBlock:^(id response) {
        AuctionSellModel *model = [AuctionSellModel modelWithDictionary:response];
        if ([model isSuccess]) {
            if (complete) {
                complete(model.data); }
        }else {
            [weakSelf showMessage:model.msg];
        }
        [weakSelf endRefreshing];
    } failBlock:^(NSError *error) {
        [weakSelf debugShowMessage:error.localizedDescription];
        [weakSelf endRefreshing];
    }];
}

/// 结束刷新
- (void)endRefreshing {
    if ([self.collectionView.mj_header isRefreshing]) {
        [self.collectionView.mj_header endRefreshing];
    }
    if ([self.collectionView.mj_footer isRefreshing]) {
        [self.collectionView.mj_footer endRefreshing];
    }
}

#pragma mark -- mark 业务逻辑

/// 刷新商铺
/// @param model model
- (void)refreshContentViewWith:(StoreHomeInfoDataModel *)model {
    _titleLabel.text = model.name;
    _desLabel.text = model.describes;
    [_bannerImageView sd_setImageWithURL:[NSURL URLWithString:model.img_bg] placeholderImage:SKIMAGE_NAMED(@"banner_default_img")];
    [_headerImageView sd_setImageWithURL:[NSURL URLWithString:model.img] placeholderImage:SKIMAGE_NAMED(@"auction_treasure_shop_icon_default")];
}



- (void)cellShareButtonClickWith:(NSIndexPath *)indexPath {
    
}
@end
